package com.yzcrm.erp.admin.controller;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yzcrm.erp.admin.entity.AdminApiLog;
import com.yzcrm.erp.admin.entity.AdminFile;
import com.yzcrm.erp.admin.entity.AdminMessage;
import com.yzcrm.erp.admin.service.AdminMessageService;
import com.yzcrm.erp.crm.common.CrmExcelUtil;
import com.yzcrm.swagger.annotation.ActionApi;
import com.yzcrm.swagger.annotation.Api;
import com.yzcrm.swagger.annotation.Param;
import com.yzcrm.swagger.annotation.Params;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.R;

import cn.hutool.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息提醒
 * @author zhangzhiwei
 */
@Api(remark = "系统：消息提醒")
public class AdminMessageController extends Controller {

    @Inject
    private AdminMessageService adminMessageService;

    /**
     * 查询用户个人消息
     */
    @ActionApi(summary = "查询用户个人消息", remark="查询用户个人消息")
    @Params({
            @Param(name="page", remark="页码 1开始", dataType="int", defaultValue="", required=false),
            @Param(name="limit", remark="每页数据条数", dataType="int", defaultValue="", required=false)
    })
    public void queryMessage(@Para("page") Integer page, @Para("limit") Integer limit){

        R r = adminMessageService.queryMessage(BaseUtil.getUserId(), page, limit);

        renderJson(r);
    }


    /**
     * 消息阅读
     */
    @ActionApi(summary = "消息阅读", remark="消息阅读")
    @Params({
            @Param(name="messageId", remark="消息Id", dataType="int", defaultValue="", required=false)
    })
    public void readMessage(@Para("messageId") Integer messageId){

        renderJson(adminMessageService.readMessage(messageId));
    }

    /**
     * 个人未查看消息总数
     */
    @ActionApi(summary = "个人未查看消息总数", remark="个人未查看消息总数")
    public void unreadMessageCount (){

        renderJson(adminMessageService.unreadMessageCount(BaseUtil.getUserId()));
    }




    /**
     * 查询当前导入数量
     * @param messageId 消息ID
     * @author zhangzhiwei
     */
    public void queryImportNum(@Para("messageId") Long messageId){
        Integer num = CrmExcelUtil.getThreadMapNum(messageId);
        renderJson(R.ok().put("data",num));
    }

    /**
     * 终止当前导入
     * @param messageId 消息ID
     * @author zhangzhiwei
     */
    public void stopImport(@Para("messageId") Long messageId){
        AdminMessage adminMessage=AdminMessage.dao.findById(messageId);
        if(adminMessage==null||!adminMessage.getCreateUser().equals(BaseUtil.getUserId())){
            renderJson(R.noAuth());
            return;
        }
        CrmExcelUtil.interrupt(messageId);
        renderJson(R.ok());
    }

    /**
     * 下载错误数据
     * @param messageId 消息ID
     * @author zhangzhiwei
     */
    public void downImportError(@Para("messageId") Long messageId){
        AdminMessage adminMessage=AdminMessage.dao.findById(messageId);
        if(adminMessage==null){
            renderNull();
            return;
        }
        AdminFile adminFile=AdminFile.dao.findById(adminMessage.getTypeId());
        if(adminFile!=null&&adminFile.getCreateUserId().equals(BaseUtil.getUserId())){
            File file=new File(adminFile.getPath());
            if(file.exists()){
                renderFile(file,"import_error.xlsx");
                return;
            }
        }
        renderNull();
    }

    /**
     * 查询当前导入详情
     * @param messageId 消息ID
     * @author zhangzhiwei
     */
    public void queryImportInfo(@Para("messageId") Long messageId){
        AdminMessage adminMessage=AdminMessage.dao.findById(messageId);
        if(adminMessage!=null){
            renderJson(R.ok().put("totalSize",adminMessage.getTitle()).put("errSize",adminMessage.getContent()));
        }else {
            renderJson(R.ok().put("totalSize",0).put("errSize",0));
        }
    }
    
    /**
     * 	@author lg
     * 	调用天眼查API
     * 
     */
    
    public void queryTianYanChaAPI(@Para("content") String content){
    	if(content == null || content.length() <= 0) {
    		renderJson(R.error("查询内容无效")); 
    		return;
    	}
        StringBuffer url = new StringBuffer();
        String tianYanChaHttp = Db.queryStr("select value from yzcrm_admin_config where name = 'TianYanChaHttp'");
        String tianYanChaToken = Db.queryStr("select value from yzcrm_admin_config where name = 'TianYanChaToken'");
        Map<String, String> data = new HashMap<String, String>();
        data.put("word",content);
        url.append(tianYanChaHttp);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", tianYanChaToken);
        String json = HttpKit.get(url.toString(),data,headers);
        JSONObject jsonObject = new JSONObject(json);
        if(jsonObject.getObj("result") != null) {
//        	记录天眼查的搜索记录
        	AdminApiLog adminApiLog = new AdminApiLog();
        	adminApiLog.setUserId(BaseUtil.getUser().getUserId());
        	adminApiLog.setValue(content);
        	adminApiLog.setType("TianYanCha");
        	adminApiLog.save();
        }
        renderJson(R.ok().put("data",jsonObject));
    }
}
